/**
 * @Author：ming
 * @Date：2023/10/30 9:26 PM
 * @Filename：Hot23
 */

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 * @author ming
 */
public class Hot23 {
}

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {

        if(lists.length==0){
            return null;
        }

        ArrayList<ListNode> myList = new ArrayList<>();
        for (ListNode list : lists) {
            while (list!=null){
                myList.add(list);
                list = list.next;
            }
        }
        if(myList.size()==0){
            return null;
        }
       Collections.sort(myList, new Comparator<ListNode>() {
           @Override
           public int compare(ListNode o1, ListNode o2) {
               return o1.val-o2.val;
           }
       });




        for (int i = 0; i < myList.size()-1; i++) {
            myList.get(i).next = myList.get(i+1);
        }
        myList.get(myList.size()-1).next=null;

        return myList.get(0);


    }
}
